## Snakes on a Payload
## Copyright (C) 2011 CORE Security Technologies
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
##
## Authors:
## 2011/09/11 - Pedro Varangot (pvarangot@)
## 2011/09/11 - Fernando Russ (fruss@)

import os
import json

class Lib(object):
    def __init__(self, name):
        self.name = name

class LibStore(object):
    def __init__(self, arch):
        self.arch = arch
    def all(self): raise Exception("not-implemented: LibStore.all")
    def byName(self, name): raise Exception("not-implemented: LibStore.byName")

class JsonLib( Lib ):
    def __init__(self, path):
        self.path = path
        Lib.__init__(self, os.path.basename(path)[:-5] )        
        with open(path, "r") as f:
            self._properties = json.load( f )            
    @property
    def exportAs(self):
        return self._properties["export-as"]
    
    @property
    def symbols(self):        
        return self._properties["symbols"]

        
class JsonLibStore( LibStore ):
    def __init__(self, arch):
        LibStore.__init__(self, arch)
        self.libs_path = os.path.join( os.path.dirname(__file__),"..","bld",arch.NAME, "libs")                            
        self.index_by_name = self.__build_index()
        
    def __build_index(self):
        _index = {}
        _index = {}
        for root, dirs, files in os.walk(self.libs_path):                        
            for filename in files:
                if filename.endswith(".json"):
                    
                    fullpath = os.path.join(root, filename)                    
                    jslib = JsonLib( os.path.join(root, filename) )                                    
                    #print "loading %s -> %s" % (jslib.name, fullpath)
                    _index[jslib.name] = jslib
        return _index
                
    def all(self):
        for lib in self.index_by_name.values():
            yield lib

    def byName(self, name):
        lib = self.index_by_name.get(name, None)
        if lib == None:
            raise Exception("invalid lib name '%s' for '%s'" % (name, self.arch.NAME) )
        return lib
